package com.cater.talents.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.cater.utils.RandomUtil;

import net.coobird.thumbnailator.Thumbnails;

/**
 * @author yong
 * @Date 2017年12月23日-下午2:14:54
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController {
	private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
	private static final String UPLOAD_PATH = "/static/ckeditor/";

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param response
	 * @param file     上传的文件，支持多文件
	 * @throws Exception
	 */
	@RequestMapping("/insert")
	@ResponseBody
	public Map<String, Object> insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile[] file) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		String filePath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
		Calendar date = Calendar.getInstance();
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		SimpleDateFormat month = new SimpleDateFormat("MM");
		SimpleDateFormat day = new SimpleDateFormat("dd");
		String datetime = year.format(date.getTime()) + "/" + month.format(date.getTime()) + "/"
				+ day.format(date.getTime()) + "/";
		File files = null;
		String ext = null;//
		String path = null;
		try {
			//
			if (file != null && file.length > 0) {
				for (int i = 0; i < file.length; i++) {
					ext = FilenameUtils.getExtension(file[i].getOriginalFilename());
					// 保存图片 File位置 （全路径） /upload/fileName.jpg
					// 相对路径
					path = "/" + datetime + RandomUtil.generateLowernum(12) + "." + ext;
					files = new File(filePath + datetime);
					if (!files.exists()) {
						files.mkdirs();
					}
					if (ext.equals("jpg") || ext.equals("png") || ext.equals("bmp")) {
						file[i].transferTo(new File(filePath + path));
						Thumbnails.of(filePath + path).scale(1f).outputQuality(0.25f).toFile(filePath + path);
					}
				}
			}
			json.put("success", "/static/upload" + path);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/uploadImg")
	public void uplodaImg(@RequestParam("upload") MultipartFile file, //
			HttpServletRequest request, //
			HttpServletResponse response)//
	{

		try {
			String proPath = request.getSession().getServletContext().getRealPath("/");
			String proName = request.getContextPath();
			String path = proPath + UPLOAD_PATH;
			File realPath = new File(path);
			if (!realPath.exists()) {
				realPath.mkdirs();
			}
			PrintWriter out = response.getWriter();
			String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
			String fileName = file.getOriginalFilename();
			String uploadContentType = file.getContentType();
			String expandedName = "";
			if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				expandedName = ".jpg";
			} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
				expandedName = ".png";
			} else if (uploadContentType.equals("image/gif")) {
				expandedName = ".gif";
			} else if (uploadContentType.equals("image/bmp")) {
				expandedName = ".bmp";
			} else {
				out.println("<script type=\"text/javascript\">");
				out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'',"
						+ "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
				out.println("</script>");
				return;
			}
			if (file.getSize() > 1024 * 1024 * 2) {
				out.println("<script type=\"text/javascript\">");
				out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",''," + "'文件大小不得大于2M');");
				out.println("</script>");
				return;
			}
			DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			fileName = df.format(new Date()) + expandedName;
			file.transferTo(new File(path + "/" + fileName));
			// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'"
					+ "/hunter/static/ckeditor/" + fileName + "','')");
			out.println("</script>");
			return;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/uploadFile")
	@ResponseBody
	public JSONObject uploadFile(@RequestParam("files") MultipartFile[] file, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		String filePath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
		Calendar date = Calendar.getInstance();
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		SimpleDateFormat month = new SimpleDateFormat("MM");
		SimpleDateFormat day = new SimpleDateFormat("dd");
		String datetime = year.format(date.getTime()) + "/" + month.format(date.getTime()) + "/"
				+ day.format(date.getTime()) + "/";
		File files = null;
		String ext = null;//
		String path = null;
		try {
			//

			if (file != null && file.length > 0) {
				for (int i = 0; i < file.length; i++) {
					ext = FilenameUtils.getExtension(file[i].getOriginalFilename());
					// 相对路径
					path = "/" + datetime + RandomUtil.generateLowernum(12) + "." + ext;
					files = new File(filePath + datetime);
					if (!files.exists()) {
						files.mkdirs();
					}
					file[i].transferTo(new File(filePath + path));
				}
				json.put("code", 200);
				json.put("path", "/static/upload" + path);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 500);
		}
		return json;

	}

}
